package org.itboys.mobile.controller;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.SundayMemberDto;
import org.itboys.mobile.dto.order.OrderIncomeDTO;
import org.itboys.mobile.dto.order.OrderWaitDto;
import org.itboys.mobile.entity.mongo.*;
import org.itboys.mobile.entity.mysql.order.PearlOrder;
import org.itboys.mobile.entity.mysql.wallet.PearlIncomRecord;
import org.itboys.mobile.service.mongo.mobile.*;
import org.itboys.mobile.service.mysql.mobile.order.PearlOrderService;
import org.itboys.mobile.service.mysql.mobile.wallet.PearlIncomService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created on 2017/10/30.
 * @author 朱坤涛
 * 会员相关的Api接口
 */
@Controller
@RequestMapping("/sunday/mobile/shop")
public class SundayMobileShopController extends BaseController{
    @Autowired
    private ShopSaleService shopSaleService;
    @Autowired
    private PearlIncomService incomService;
    @Autowired
    private PearlOrderService orderService;
    @Autowired
    private SundayMobileMemberService mobileMemberService;
    @Autowired
    private PearlAccountService accountService;
    @Autowired
    private ShareRecordService shareRecordService;
    @Autowired
    private PushMessageService pushMessageService;
    @Autowired
    private OrderItemService orderItemService;
    @ApiOperation(value = "设置店铺名称")
    @RequestMapping(value = "/AbSetName", method = RequestMethod.POST)
    public void AbSetName(
            @ApiParam(required = true,name = "name",value = "名称")@RequestParam(value = "name",required = true)String name,
            @ApiParam(required = true,name = "memberId",value = "会员Id")@RequestParam(value = "memberId",required = true)Long memberId,
            HttpServletRequest request,HttpServletResponse response
    ){
        try {
            SundayMember member = mobileMemberService.getById(memberId);
            member.setShopName(name);
            mobileMemberService.update(member);
            AjaxUtils.renderJson(response,ResultPageDOHelper.getMsgResultDO(member,"success"));
        }catch (Exception e){
            e.printStackTrace();
            AjaxUtils.renderJson(response,ResultPageDOHelper.getErrorResultDO(-1,"系统错误"));
        }
    }

    @ApiOperation(value = "上/下架产品")
    @RequestMapping(value = "/addPro",method = RequestMethod.POST)
    public void addPro(
            @ApiParam(required = true,name = "memberId",value = "会员Id")@RequestParam(value = "memberId",required = true)Long memberId,
            @ApiParam(required =true,name = "type",value = "1-上架 2-下架")@RequestParam(value = "type",required = true)Integer type,
            @ApiParam(required = false, name = "productId", value = "产品Id") @RequestParam(value = "productId", required = false) Long productId,
            @ApiParam(required = false, name = "brandId", value = "品牌Id") @RequestParam(value = "brandId", required = false) Long brandId,HttpServletResponse response
    ){
        try {
            Integer count = 0;
            Map<String,Object> map = new HashMap<>();
            Map<String,Object> param = new HashMap<>();
            map.put("memberId",memberId);
            param.put("memberId",memberId);
            param.put("status",1);
            ShopSale shopSale = new ShopSale();
            shopSale.setMemberId(memberId);
            if (productId!=null){
                shopSale.setProductId(productId);
                map.put("productId",productId);
                param.put("brandId",0);
            }
            if (brandId!=null){
                shopSale.setBrandId(brandId);
                map.put("brandId",brandId);
                param.put("productId",0);
            }
            List<ShopSale> list = shopSaleService.list(map);
            if (list!=null &&list.size()>0){
                ShopSale sale = list.get(0);
                if (sale.getStatus()==0){
                    if (type == 1){
                        shopSaleService.update(sale.getId(),"statis",1);
                    }
                }else {
                    if (type == 2){
                        shopSaleService.update(sale.getId(),"status",0);
                    }
                }
            }else {
                shopSaleService.save(shopSale);
            }
            List<ShopSale> sales = shopSaleService.list(param);
            AjaxUtils.renderJson(response,ResultPageDOHelper.getMsgResultDO(sales!=null&&sales.size()>0?sales.size():0,"success"));
        }catch (Exception e){
            e.printStackTrace();
            AjaxUtils.renderJson(response,ResultPageDOHelper.getErrorResultDO(-1,"系统错误"));
        }
    }

    @ApiOperation(value = "我的收益")
    @RequestMapping(value = "/MyProfit",method = RequestMethod.POST)
    public void MyProfit(
            @ApiParam(required = true,name = "memberId",value = "会员Id")@RequestParam(value = "memberId",required = true)Long membeiId,
            HttpServletResponse response
    ){
        try {
            Map<String,Object> resultMap = incomService.getProfit(membeiId);
            AjaxUtils.renderJson(response,ResultPageDOHelper.getMsgResultDO(resultMap,"success"));
        }catch (Exception e){
            e.printStackTrace();
            AjaxUtils.renderJson(response,ResultPageDOHelper.getErrorResultDO(-1,"系统异常！"));
        }
    }

    @ApiOperation(value = "销售管理")
    @RequestMapping(value = "/SalesManagement",method = RequestMethod.POST)
    public void  SalesManagement(
            @ApiParam(required = true, name = "memberId", value = "会员Id") @RequestParam(value = "memberId", required = true) Long memberId,
            @ApiParam(required = false, name = "startTime", value = "开始时间") @RequestParam(value = "startTime", required = false) Date startTime,
            @ApiParam(required = false, name = "endTime", value = "结束时间") @RequestParam(value = "endTime", required = false) Date endTime,HttpServletResponse response
    ){
        try{
            Map<String, Object> map = new HashMap<>();
            map.put("userId", memberId);
            if(startTime != null) {
                map.put("startTime", startTime);
            }
            if(endTime != null) {
                map.put("endTime", endTime);
            }
            List<PearlIncomRecord> list = incomService.findListByShop(map);
            List<OrderIncomeDTO> dtos = new ArrayList<>();
            for (PearlIncomRecord record : list) {
                PearlOrder order = orderService.find(record.getObjId());
                if (order != null) {
                    OrderIncomeDTO dto = new OrderIncomeDTO(order.getTotalAmount(), record.getAmount().doubleValue());
                    dtos.add(dto);
                }
            }
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(dtos, "success"));
        }catch (Exception e){
            e.printStackTrace();
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统异常!"));
        }
    }

    @ApiOperation(value = "业绩管理")
    @RequestMapping(value = "/SaleRecord",method = RequestMethod.POST)
    public void SaleRecord(
            @ApiParam(required = true, name = "memberId", value = "会员Id") @RequestParam(value = "memberId", required = true) Long memberId,HttpServletResponse response
    ){
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", memberId);
            map.put("sale", 1);
            List<SundayMember> members = mobileMemberService.findByField("recId", memberId);
            Integer count = 0;
            BigDecimal total = new BigDecimal(0);
            List<SundayMemberDto> dtos = new ArrayList<>();
            if(members != null && members.size() > 0) {
                count = members.size();
                for (SundayMember member : members) {
                    map.put("fromUserId", member.getId());
                    BigDecimal totalProfit = incomService.getIncomeAmountByMap(map);
                    SundayMemberDto dto = new SundayMemberDto(member.getMemberLevel(), member.getNickName(), totalProfit.doubleValue());
                    dtos.add(dto);
                    total = total.add(totalProfit);

                }
            }
            map.clear();
            map.put("count", count);
            map.put("total", total);
            map.put("list", dtos);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(map, "success"));
        }catch (Exception e){
            e.printStackTrace();
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统异常!"));
        }
    }



    @ApiOperation(value = "店铺统计(订单/销售/收益/粉丝)")
    @RequestMapping(value = "/AyShopCount", method = RequestMethod.POST)
    public void AyShopCount(
            @ApiParam(required = true, name = "memberId", value = "会员Id") @RequestParam(value = "memberId", required = true) Long memberId,HttpServletResponse response) {
        try {
            //统计订单
            Map<String, Object> map = new HashMap<>();
            map.put("createTime >", new DateTime(new Date()).minusDays(1).toDate());
            map.put("createTime <", new DateTime(new Date()).plusDays(1).toDate());
            map.put("status >", 0);
            List<String> arr = new ArrayList<>();
            arr.add("memberId");
            arr.add("userId");
            map.put("list_" + memberId, arr);
            List<PearlOrder> list = orderService.select(map);
            //统计收益
            BigDecimal amount = incomService.getMonthIncomeMember(memberId);
            //统计粉丝
            List<SundayMember> memberList = mobileMemberService.findByField("recId", memberId);
            //统计销售
            BigDecimal amount2 = new BigDecimal(0);
          /*  for (Member member : memberList) {
                BigDecimal aaa = incomeRecordService.getMonthIncomeMember2(member.getId());
                amount2 = amount2.add(aaa);
            }*/
            amount2 = incomService.getMonthIncomeMember2(memberId);
            Map<String, Object> result = new HashMap<>();
            result.put("todayOrder", list.size());
            result.put("monthSale", amount2);
            result.put("monthTotalScale", amount);
            result.put("memberSize", memberList.size());
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(result, "success"));
        } catch (Exception e) {
            e.printStackTrace();
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统异常!"));
        }
    }

    @ApiOperation(value = "修改店铺信息")
    @RequestMapping(value = "/AzEditInfo", method = RequestMethod.POST)
    public void AzEditInfo(
            @ApiParam(required = true, name = "memberId", value = "用户Id") @RequestParam(value = "memberId", required = true) Long memberId,
            @ApiParam(required = false, name = "shopName", value = "店铺名称") @RequestParam(value = "shopName", required = false) String shopName,
            @ApiParam(required = false, name = "shopLogo", value = "店铺头像") @RequestParam(value = "shopLogo", required = false) String shopLogo,
            @ApiParam(required = false, name = "shopImage", value = "店招") @RequestParam(value = "shopImage", required = false) String shopImage,
            @ApiParam(required = false, name = "shopInfo", value = "店铺介绍") @RequestParam(value = "shopInfo", required = false) String shopInfo,
            @ApiParam(required = false, name = "path", value = "二维码") @RequestParam(value = "path", required = false) String path,
            HttpServletResponse response) {
        try {
            SundayMember member = mobileMemberService.getById(memberId);
            if(StringUtils.isNotBlank(shopName)) {
                member.setShopName(shopName);
            }
            if(StringUtils.isNotBlank(shopLogo)) {
                member.setShopLogo(shopLogo);
            }
            if(StringUtils.isNotBlank(shopImage)) {
                member.setShopImage(shopImage);
            }
            if(StringUtils.isNotBlank(shopInfo)) {
                member.setShopInfo(shopInfo);
            }
            if(StringUtils.isNotBlank(path)) {
                member.setPath(path);
            }
            mobileMemberService.update(member);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(mobileMemberService.getMemberInfo(member), "OK"));
        } catch (Exception e) {
            e.printStackTrace();
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统错误!"));
        }
    }

    @ApiOperation(value = "累计收益详情")
    @RequestMapping(value = "/BbProfitDetail", method = RequestMethod.POST)
    public void BbProfitDetail(
            @ApiParam(required = true, name = "memberId", value = "会员Id") @RequestParam(value = "memberId", required = true) Long memberId,HttpServletResponse response) {
        try {
            SundayMember member = mobileMemberService.getById(memberId);
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("userId", memberId);
            if(member.getMemberLevel() > 3) {
                paramMap.put("sale", 1); //收益
            } else {
                paramMap.put("objType", 1);
            }
            Map<String, Object> result = incomService.getIncomeMap(paramMap);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(result, "success"));
        } catch (Exception e) {
            e.printStackTrace();
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统异常!"));
        }
    }

    @ApiOperation(value = "分享明细记录")
    @RequestMapping(value = "/BeShareRecode", method = RequestMethod.POST)
    public void BeShareRecode(@ApiParam(required = true, name = "memberId", value = "会员Id") @RequestParam Long memberId,
                              HttpServletResponse response) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("recId", memberId);
            map.put("orderByKey", "-createTime");
            List<ShareRecode> list = shareRecordService.list(map);
            for (ShareRecode recode : list) {
                SundayMember member = mobileMemberService.getById(recode.getMemberId());
                if(member != null) {
                    recode.setNickName(member.getNickName());
                    recode.setMobile(member.getMobile());
                }
            }
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(list, "success"));
        } catch (Exception e) {
            logger.error("getCategory error!", e);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "error!"));
        }
    }

    @ApiOperation(value = "消息推送")
    @RequestMapping(value = "/BfMessage", method = RequestMethod.POST)
    public void BfMessage(@ApiParam(required = true, name = "memberId", value = "会员Id") @RequestParam Long memberId,
                          HttpServletResponse response) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("memberId", memberId);
            map.put("orderByKey", "-ct");
            List<PushMessage> list = pushMessageService.list(map);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(list, "success"));
        } catch (Exception e) {
            logger.error("getCategory error!", e);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "error!"));
        }
    }

    @ApiOperation(value = "删除推送消息")
    @RequestMapping(value = "/BgDelMessage", method = RequestMethod.POST)
    public void BgDelMessage(@ApiParam(required = true, name = "id", value = "消息Id") @RequestParam Long id,
                             HttpServletResponse response) {
        try {
            pushMessageService.delete(id);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(null, "success"));
        } catch (Exception e) {
            logger.error("getCategory error!", e);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "error!"));
        }
    }

    @ApiOperation(value = "待收收益明细")
    @RequestMapping(value = "/BiWaitDetail", method = RequestMethod.POST)
    public void BiWaitDetail(@ApiParam(required = true, name = "memberId", value = "会员Id") @RequestParam Long memberId,
                             @ApiParam(required = false, name = "pageNo", value = "第几页") @RequestParam(value = "pageNo", required = false) Integer pageNo,
                             @ApiParam(required = false, name = "pageSize", value = "每页行数") @RequestParam(value = "pageSize", required = false) Integer pageSize,
                             HttpServletResponse response) {
        try {
            List<OrderWaitDto> dtos = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            if (pageSize == null) {
                pageSize = 10;
            }
            if (pageNo == null) {
                pageNo = 1;
            }
            Long rowStart = (long) ((pageNo - 1) * pageSize);
            map.put("rowStart", rowStart);
            map.put("pageSize", pageSize);
            map.put("objType", 1);
            map.put("userId", memberId);
            map.put("isConfirm", 0);
            List<PearlIncomRecord> list = incomService.findListByMap(map);
            List<PearlOrder> orderList = new ArrayList<>();
            for (PearlIncomRecord record : list) {
                if(record.getObjType() == 1 && record.getIsConfirm() == 0) {
                    PearlOrder order = orderService.find(record.getObjId());
                    if(order != null) {
                        order.setScale(record.getAmount().toString());
                        orderList.add(order);
                    }
                }
            }
            for (PearlOrder order : orderList) {
                List<OrderItem> items = orderItemService.findByField("orderId", order.getId());
                OrderWaitDto dto = new OrderWaitDto(order,items);
                SundayMember member = mobileMemberService.getById(order.getMemberId());
                dto.setBuyerName(member.getNickName());
                dtos.add(dto);
            }
            AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(dtos, "success"));
        } catch (Exception e) {
            logger.error("getCategory error!", e);
            AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "error!"));
        }
    }
}
